package com.expert.miniapp.service.impl;

import com.expert.miniapp.config.WechatConfig;
import com.expert.miniapp.service.WechatService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * WechatServiceImpl - 微信服务实现类
 *
 * @author System
 * @since 2025-01-14
 */
@Service
public class WechatServiceImpl implements WechatService {

    private static final Logger logger = LoggerFactory.getLogger(WechatServiceImpl.class);

    @Autowired
    private WechatConfig wechatConfig;

    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;

    public WechatServiceImpl() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public Map<String, String> code2Session(String code) throws Exception {
        // 构建请求URL
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                wechatConfig.getCode2sessionUrl(),
                wechatConfig.getAppId(),
                wechatConfig.getAppSecret(),
                code
        );

        logger.info("调用微信code2Session接口: appid={}, code={}", wechatConfig.getAppId(), code);

        // 发送HTTP请求
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new Exception("微信API调用失败: HTTP " + response.code());
            }

            String responseBody = response.body().string();
            logger.info("微信code2Session响应: {}", responseBody);

            // 解析响应JSON
            JsonNode jsonNode = objectMapper.readTree(responseBody);

            // 检查是否有错误
            if (jsonNode.has("errcode")) {
                int errcode = jsonNode.get("errcode").asInt();
                String errmsg = jsonNode.get("errmsg").asText();
                logger.error("微信API返回错误: errcode={}, errmsg={}", errcode, errmsg);
                throw new Exception("微信登录失败: " + errmsg);
            }

            // 提取openid和session_key
            String openid = jsonNode.get("openid").asText();
            String sessionKey = jsonNode.has("session_key") ? jsonNode.get("session_key").asText() : null;

            Map<String, String> result = new HashMap<>();
            result.put("openid", openid);
            result.put("session_key", sessionKey);

            logger.info("成功获取openid: {}", openid);
            return result;

        } catch (Exception e) {
            logger.error("调用微信code2Session接口失败", e);
            throw e;
        }
    }
}
